package com.campus.food.controller;

import com.campus.food.model.entity.Merchant;
import com.campus.food.service.MerchantService;
import com.campus.food.util.Result;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 商家控制器
 * 处理商家相关的HTTP请求
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/merchants")
@Validated
public class MerchantController {
    
    @Autowired
    private MerchantService merchantService;
    
    /**
     * 申请商家入驻
     * POST /api/merchants/apply
     */
    @PostMapping("/apply")
    public Result<Merchant> applyMerchant(@Valid @RequestBody Merchant merchant) {
        try {
            Merchant savedMerchant = merchantService.applyMerchant(merchant);
            return Result.success("申请提交成功，请等待审核", savedMerchant);
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("申请失败，请稍后重试");
        }
    }
    
    /**
     * 根据ID获取商家信息
     * GET /api/merchants/{id}
     */
    @GetMapping("/{id}")
    public Result<Merchant> getMerchantById(@PathVariable @NotNull Long id) {
        try {
            Merchant merchant = merchantService.getMerchantById(id);
            return Result.success(merchant);
        } catch (BusinessException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.error("获取商家信息失败");
        }
    }
    
    /**
     * 根据用户ID获取商家信息
     * GET /api/merchants/user/{userId}
     */
    @GetMapping("/user/{userId}")
    public Result<Merchant> getMerchantByUserId(@PathVariable @NotNull Long userId) {
        try {
            Merchant merchant = merchantService.getMerchantByUserId(userId);
            if (merchant == null) {
                return Result.notFound("该用户尚未申请商家入驻");
            }
            return Result.success(merchant);
        } catch (Exception e) {
            return Result.error("获取商家信息失败");
        }
    }
    
    /**
     * 更新商家信息
     * PUT /api/merchants/{id}
     */
    @PutMapping("/{id}")
    public Result<String> updateMerchant(@PathVariable @NotNull Long id,
                                       @RequestBody Merchant merchant) {
        try {
            merchant.setId(id);
            boolean success = merchantService.updateMerchant(merchant);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新商家信息失败");
        }
    }
    
    /**
     * 更新商家审核状态（管理员专用）
     * PUT /api/merchants/{id}/status
     */
    @PutMapping("/{id}/status")
    public Result<String> updateMerchantStatus(@PathVariable @NotNull Long id,
                                             @RequestParam @NotNull Integer status) {
        try {
            boolean success = merchantService.updateMerchantStatus(id, status);
            if (success) {
                String message = getStatusMessage(status);
                return Result.success(message);
            } else {
                return Result.error("状态更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新商家状态失败");
        }
    }
    
    /**
     * 更新商家营业状态
     * PUT /api/merchants/{id}/business-status
     */
    @PutMapping("/{id}/business-status")
    public Result<String> updateBusinessStatus(@PathVariable @NotNull Long id,
                                             @RequestParam @NotNull Integer businessStatus) {
        try {
            boolean success = merchantService.updateBusinessStatus(id, businessStatus);
            if (success) {
                String message = businessStatus == 1 ? "店铺已开始营业" : "店铺已暂停营业";
                return Result.success(message);
            } else {
                return Result.error("营业状态更新失败");
            }
        } catch (BusinessException e) {
            e.printStackTrace();
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新营业状态失败");
        }
    }
    
    /**
     * 获取商家列表（分页）
     * GET /api/merchants
     */
    @GetMapping
    public Result<List<Merchant>> getMerchantList(@RequestParam(defaultValue = "1") int page,
                                                @RequestParam(defaultValue = "10") int size,
                                                @RequestParam(required = false) String shopName,
                                                @RequestParam(required = false) Integer status,
                                                @RequestParam(required = false) Integer businessStatus) {
        try {
            List<Merchant> merchants = merchantService.getMerchantList(page, size, shopName, status, businessStatus);
            long total = merchantService.getMerchantCount(shopName, status, businessStatus);
            return Result.success(merchants, total);
        } catch (Exception e) {
            return Result.error("获取商家列表失败");
        }
    }
    
    /**
     * 根据审核状态获取商家列表
     * GET /api/merchants/status/{status}
     */
    @GetMapping("/status/{status}")
    public Result<List<Merchant>> getMerchantsByStatus(@PathVariable @NotNull Integer status) {
        try {
            List<Merchant> merchants = merchantService.getMerchantsByStatus(status);
            return Result.success(merchants);
        } catch (Exception e) {
            return Result.error("获取商家列表失败");
        }
    }
    
    /**
     * 根据营业状态获取商家列表
     * GET /api/merchants/business-status/{businessStatus}
     */
    @GetMapping("/business-status/{businessStatus}")
    public Result<List<Merchant>> getMerchantsByBusinessStatus(@PathVariable @NotNull Integer businessStatus) {
        try {
            List<Merchant> merchants = merchantService.getMerchantsByBusinessStatus(businessStatus);
            return Result.success(merchants);
        } catch (Exception e) {
            return Result.error("获取商家列表失败");
        }
    }
    
    /**
     * 获取营业中的商家列表（用户端）
     * GET /api/merchants/open
     */
    @GetMapping("/open")
    public Result<List<Merchant>> getOpenMerchants(@RequestParam(defaultValue = "1") int page,
                                                 @RequestParam(defaultValue = "10") int size,
                                                 @RequestParam(required = false) String shopName,
                                                 @RequestParam(required = false) Double minRating,
                                                 @RequestParam(required = false) Double maxRating,
                                                 @RequestParam(required = false) Integer minSales,
                                                 @RequestParam(required = false) Integer maxSales,
                                                 @RequestParam(required = false) String orderBy) {
        try {
            List<Merchant> merchants = merchantService.getOpenMerchants(page, size, shopName, minRating, maxRating, minSales, maxSales, orderBy);
            long total = merchantService.getOpenMerchantsCount(shopName, minRating, maxRating, minSales, maxSales);
            return Result.success(merchants, total);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取商家列表失败");
        }
    }
    
    /**
     * 更新商家评分
     * PUT /api/merchants/{id}/rating
     */
    @PutMapping("/{id}/rating")
    public Result<String> updateRating(@PathVariable @NotNull Long id,
                                     @RequestParam @NotNull Double rating) {
        try {
            boolean success = merchantService.updateRating(id, rating);
            if (success) {
                return Result.success("评分更新成功");
            } else {
                return Result.error("评分更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新商家评分失败");
        }
    }
    
    /**
     * 更新商家月销量
     * PUT /api/merchants/{id}/monthly-sales
     */
    @PutMapping("/{id}/monthly-sales")
    public Result<String> updateMonthlySales(@PathVariable @NotNull Long id,
                                           @RequestParam @NotNull Integer monthlySales) {
        try {
            boolean success = merchantService.updateMonthlySales(id, monthlySales);
            if (success) {
                return Result.success("月销量更新成功");
            } else {
                return Result.error("月销量更新失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新商家月销量失败");
        }
    }
    
    /**
     * 检查用户是否已申请商家
     * GET /api/merchants/check/user/{userId}
     */
    @GetMapping("/check/user/{userId}")
    public Result<Boolean> checkMerchantByUserId(@PathVariable @NotNull Long userId) {
        try {
            boolean exists = merchantService.existsByUserId(userId);
            return Result.success(exists);
        } catch (Exception e) {
            return Result.error("检查失败");
        }
    }
    
    /**
     * 删除商家（管理员专用）
     * DELETE /api/merchants/{id}
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteMerchant(@PathVariable @NotNull Long id) {
        try {
            boolean success = merchantService.deleteMerchant(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("删除商家失败");
        }
    }
    
    /**
     * 审核商家（管理员专用）
     * POST /api/merchants/{id}/audit
     */
    @PostMapping("/{id}/audit")
    public Result<String> auditMerchant(@PathVariable @NotNull Long id,
                                      @RequestParam @NotNull Integer status,
                                      @RequestParam(required = false) String reason) {
        try {
            boolean success = merchantService.auditMerchant(id, status, reason);
            if (success) {
                String message = status == 1 ? "审核通过" : "审核拒绝";
                return Result.success(message);
            } else {
                return Result.error("审核失败");
            }
        } catch (BusinessException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("审核商家失败");
        }
    }
    
    /**
     * 根据状态码获取状态描述
     */
    private String getStatusMessage(Integer status) {
        switch (status) {
            case 0:
                return "待审核";
            case 1:
                return "审核通过";
            case 2:
                return "审核拒绝";
            default:
                return "状态更新成功";
        }
    }
    
    /**
     * 获取商家统计数据
     * GET /api/merchants/{id}/statistics
     */
    @GetMapping("/{id}/statistics")
    public Result<Object> getStatistics(@PathVariable @NotNull Long id,
                                      @RequestParam(required = false) String startTime,
                                      @RequestParam(required = false) String endTime) {
        try {
            Object statistics = merchantService.getStatistics(id, startTime, endTime);
            return Result.success(statistics);
        }  catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败");
        }
    }
    
    /**
     * 获取商家订单趋势数据
     * GET /api/merchants/{id}/order-trend
     */
    @GetMapping("/{id}/order-trend")
    public Result<List<Object>> getOrderTrend(@PathVariable @NotNull Long id,
                                            @RequestParam(required = false) String startTime,
                                            @RequestParam(required = false) String endTime,
                                            @RequestParam(defaultValue = "day") String timeUnit) {
        try {
            List<Object> trendData = merchantService.getOrderTrend(id, startTime, endTime, timeUnit);
            return Result.success(trendData);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取订单趋势数据失败");
        }
    }
    
    /**
     * 获取商家菜品销售占比数据
     * GET /api/merchants/{id}/food-sales-proportion
     */
    @GetMapping("/{id}/food-sales-proportion")
    public Result<List<Object>> getFoodSalesProportion(@PathVariable @NotNull Long id,
                                                     @RequestParam(required = false) String startTime,
                                                     @RequestParam(required = false) String endTime,
                                                     @RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Object> salesData = merchantService.getFoodSalesProportion(id, startTime, endTime, limit);
            return Result.success(salesData);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取菜品销售占比数据失败");
        }
    }
    
    /**
     * 获取商家订单状态分布数据
     * GET /api/merchants/{id}/order-status-distribution
     */
    @GetMapping("/{id}/order-status-distribution")
    public Result<Object> getOrderStatusDistribution(@PathVariable @NotNull Long id,
                                                   @RequestParam(required = false) String startTime,
                                                   @RequestParam(required = false) String endTime) {
        try {
            Object distributionData = merchantService.getOrderStatusDistribution(id, startTime, endTime);
            return Result.success(distributionData);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取订单状态分布数据失败");
        }
    }
    
    /**
     * 获取商家客户统计数据
     * GET /api/merchants/{id}/customer-statistics
     */
    @GetMapping("/{id}/customer-statistics")
    public Result<List<Object>> getCustomerStatistics(@PathVariable @NotNull Long id,
                                                    @RequestParam(required = false) String startTime,
                                                    @RequestParam(required = false) String endTime) {
        try {
            List<Object> customerData = merchantService.getCustomerStatistics(id, startTime, endTime);
            return Result.success(customerData);
        }  catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取客户统计数据失败");
        }
    }
    
    /**
     * 获取商家热销商品排行
     * GET /api/merchants/{id}/hot-foods
     */
    @GetMapping("/{id}/hot-foods")
    public Result<List<Object>> getHotFoods(@PathVariable @NotNull Long id,
                                          @RequestParam(required = false) String startTime,
                                          @RequestParam(required = false) String endTime,
                                          @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<Object> hotFoods = merchantService.getHotFoods(id, startTime, endTime, limit);
            return Result.success(hotFoods);
        }  catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取热销商品数据失败");
        }
    }
} 